﻿using System;
using System.Windows.Documents;
using QueryResource.Common;
using System.Windows.Media;

namespace SimpleControlLibrary.UI
{
    /// <summary>
    /// LogControl.xaml 的交互逻辑
    /// </summary>
    [System.ComponentModel.DesignTimeVisible(false)]
    public partial class LogControl
    {
        public LogControl()
        {
            InitializeComponent();
        }

        public void WriteLog(string msg, Color errorColor)
        {
            this.InvokeEx(() =>
                  {
                      if (this.cbIsClearState.IsChecked == true)
                      {
                          ClearTextNextLength(5000);
                      }
                      SetTextColor(string.Format("<--------{0}-------->", DateTime.Now.ToString("HH:mm:ss")), 
                          errorColor);
                      SetTextColor(Environment.NewLine + msg + Environment.NewLine, errorColor);

                      ScrollToEnd();
                  });
        }

        private void BtnClearLogItemClick(object sender,EventArgs e)
        {
            this.tblog.Document.Blocks.Clear();
        }

        public void ScrollToEnd()
        {
            this.InvokeEx(() => this.tblog.ScrollToEnd());
        }

        private void SetTextColor(string msg, Color c,float? size = null)
        {
            SolidColorBrush brush = new SolidColorBrush(c);
            TextRange textrange = new TextRange(tblog.Document.ContentEnd, tblog.Document.ContentEnd) {Text = msg};
            if (size != null)
            {
                textrange.ApplyPropertyValue(TextElement.FontSizeProperty, size.ToString());
            }
            textrange.ApplyPropertyValue(TextElement.ForegroundProperty, brush);
        }

        private void ClearTextNextLength(int length)
        {
            TextRange tr = new TextRange(tblog.Document.ContentStart, tblog.Document.ContentEnd);
            if (tr.Text.Length > length)
            {
                this.tblog.Document.Blocks.Clear();
            }
        }
    }
}
